<template>
  <section class="sample-section"  v-loading.lock="loading" element-loading-text="拼命加载中">
    <el-form :model="data" :rules="dataRule" ref="dataForm" label-width="160px" v-if="type === 'import'">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>注册信息导入</span>
        </div>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="注册信息模板" prop="username">
              <el-button type="text" @click="downloadfile()">点击下载模板</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="导入付款明细">
              <el-upload class="uploadBtn" ref="upload"
                         :data="{company_id: dataForm.company_id}"
                         :action="getUrl()"
                         :headers="{ token: $cookie.get('token') }"
                         :on-change="handleFileChange"
                         :on-success="handleUploadSuccess"
                         :on-error="handleUploadError"
                         :file-list="dataForm.fileList"
                         :limit="1"
                         :auto-upload="false">
                <el-button type="primary" size="small">浏览</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="选择所属企业">
              <el-select v-model="dataForm.company_id" filterable @change="companyChange" placeholder="选择所属企业">
                <el-option
                  v-for="item in companys"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="item-row">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item>
              <el-button type="danger" @click="dataFormSubmit()" :disabled="submit">导   入</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>使用说明:</span>
        </div>
        <div class="desc">
          <p class="danger-text">1. 请先正确填写注册信息模板；</p>
          <p class="danger-text">2. 下载的模板中, 表头信息请勿改动;</p>
          <p class="danger-text">3. 上传时请检查,要上传的文件中是否存在科学计数法(如:2.01709E+15),或其他不正常显示的数据,以免导入不成功;</p>
          <p class="danger-text">4. 上传的数据中,请注意身份证号与银行卡号正确,否则认证将不成功</p>
          <p class="danger-text">5. 如果上传的信息中有长数字串,请将 excle 设置成文本格式;</p>
        </div>
      </el-card>

    </el-form>

    <validate :headData="headData" :tableData="tableData" @cancel="handleCancel" v-else></validate>

  </section>
</template>

<script>
    import validate from "../member/validate";
    export default {
      name: "import",
      data () {
        return {
          loading: true,
          type: 'import',
          dataForm: {
            company_id: '',
            file_name: '',
            fileList: []
          },
          headData: [],
          tableData: [],
          search: {
            title: '',
          },
          pageIndex: 1,
          pageSize: 100,
          totalPage: 0,
          companys: [],
          tasks: []
        }
      },
      components: {
        validate
      },
      activated () {
        this.loading = false
        this.init()
      },
      methods: {
        init () {
          this.$http({
            url: this.$http.adornUrl('/company/list'),
            method: 'get',
            params: this.$http.adornParams({
              'page': this.pageIndex,
              'limit': this.pageSize,
              'title': this.search.title
            })
          }).then(({data}) => {
            let _list = data.page.list
            this.companys = _list.map(function(val, idx, _list) {
              return Object.assign({}, {'id': val.company_id, 'title': val.title})
            })
            setTimeout(() => {
              this.loading = false
            }, 500);
          })
        },
        handleCancel() {
          this.type = 'import'
          this.dataForm.fileList = []
          this.$nextTick(() => {
            this.dataForm.fileName = ''
          })
        },

        downloadfile() {
          this.$http({
            url: this.$http.adornUrl('/member/template'),
            method: 'get',
            responseType: 'blob'
          }).then((res) => {
            let _data = res.data
            let blob = new Blob([_data])
            let reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
              let a = document.createElement('a')
              a.download = '导入自然人模板.xlsx'
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              a.remove()
            }
          })
        },
        handleFileChange(file) {
          if (file.raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && file.raw.type !== 'application/vnd.ms-excel') {
            this.$message.error('文件类型错误！')
            return false
          }
          if(file.size > 3 * 1024 * 1024) {
            this.$message.error('只支持3M以内的文件上传！')
            return false
          }
          this.dataForm.file_name = file.name
        },
        handleUploadSuccess(res) {
          if(res.code === 0) {
            this.type = 'validate'
            this.headData = res.data.header
            this.tableData = res.data.list
          } else {
            this.$message.error(res.msg)
          }
          this.dataForm.fileList = []
          this.$nextTick(() => {
            this.dataForm.file_name = ''
          })
        },
        handleUploadError() {
          this.dataForm.fileList = []
          this.$nextTick(() => {
            this.dataForm.file_name = ''
          })
        },
        getUrl(type) {
          return this.$http.adornUrl(`/member/parser`)
        },
        dataFormSubmit() {
          if(!this.dataForm.file_name) {
            this.$message.error("请选择文件")
            return
          }
          if(!this.dataForm.company_id) {
            this.$message.error("请选择企业")
            return
          }
          this.$refs.upload.submit()
        }
      }
    }
</script>

<style lang="scss"  scoped>
  .box-card {
    margin-bottom: 20px;
  }
  .desc {
  .danger-text {
    color: #f56c6c;
  }
  }
</style>
